<template>
  <!-- 已签订合同清单 -->
  <el-dialog
    v-el-drag-dialog
    title="已签订合同清单"
    :visible.sync="visible"
    width="70%"
    min-width="1024px"
    append-to-body
    @close="reset"
  >
    <el-table-form ref="form">
      <el-form-item class="merge-item">
        <el-select v-model="qType" style="width: 180px; margin-right: 2px;">
          <el-option label="客户编号" value="csmCode" />
          <el-option label="客户名称" value="csmName" />
        </el-select>
        <el-input v-model="param" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="dateType" style="width: 170px; margin-right: 2px;">
          <el-option label="签署日期" :value="1" />
          <el-option label="到期时间" :value="2" />
        </el-select>
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item class="merge-item" label="操作人:">
        <el-input v-model="operatorUser" placeholder="请输入" clearable />
      </el-form-item>

      <el-form-item label="所属机构:">
        <el-tree-select
          v-model="query.orgSNNo"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: false,
            placeholder: '请选择责任机构',
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
        />
      </el-form-item>
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
        <el-button type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
      </template>
    </el-table-form>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      :immediate-fetch="false"
      @fetch="fetchData"
    />
    <div slot="footer" class="dialog-footer">
      <el-button @click="reset">关闭</el-button>
    </div>
    <order-flow ref="orderFlow" />
    <affix-list ref="affixList" @upDataTable="upDataTable" />
    <pact-info ref="pactInfo" />
  </el-dialog>
</template>

<script>
  import { queryEableContractTemplateNotSignedList, queryEableContractExport, queryExportDomain } from '@/api'
  import { parseTime } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import OrderFlow from './OrderFlow'
  import AffixList from './AffixList'
  import PactInfo from './PactInfo.vue'

  export default {
    name: 'bargain-info',
    components: {
      OrderFlow,
      AffixList,
      PactInfo
    },
    props: {
      treeData: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        parseTime,
        visible: false,
        exportDomain: '',
        temp: {},
        date: [],
        qType: 'csmCode',
        param: '',
        operatorUser: '',
        dateType: 1,
        query: {
          orgSNNo: ''
        },
        tableData: {
          total: 0,
          data: [],
          column: [
            {
              prop: 'contractId',
              label: '编号'
            },
            {
              prop: 'csmCode',
              label: '客户编号'
            },
            {
              prop: 'csmName',
              label: '客户名称'
            },
            {
              prop: 'csmAddress',
              label: '地址'
            },
            {
              prop: 'orgName',
              label: '地址所属机构'
            },
            {
              prop: 'signDate',
              label: '签署日期',
              render: (h, { row }) => <span>{ row.signDate && parseTime(row.signDate, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'expiryDate',
              label: '到期时间',
              render: (h, { row }) => <span>{ row.expiryDate && parseTime(row.expiryDate, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'certificate',
              label: '登记证书'
            },
            {
              prop: 'operatorUser',
              label: '操作人'
            },
            {
              prop: 'attachmentCount',
              label: '附件',
              render: (h, { row, $index }) => {
                return (
                  <div>
                    <el-link size='mini' onClick={() => this.showAttachmentListWin(row)}>{row.attachmentCount}</el-link>
                  </div>
                )
              }
            },
            {
              label: '操作',
              align: 'center',
              fixed: 'right',
              width: 220,
              render: (h, { row }) => {
                return (
                  <div>
                    <el-link size='mini' onClick={() => this.openDetail(row)}>详情</el-link>
                    <el-link size='mini' onClick={() => this.uploadAttachment(row)}>上传附件</el-link>
                    <el-link size='mini' onClick={() => this.changeRecord(row)}>历史记录</el-link>
                  </div>
                )
              }
            }
          ]
        }
      }
    },
    computed: {},
    created() {},
    methods: {
      async open(temp) {
        console.log('row', temp)
        this.getExportDomain()
        this.temp = temp
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          this.$nextTick(() => {
            this.$refs.lbTable.fetch({ currentPage: 1 })
          })
        })
      },
      // 查询
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 更新数据
      upDataTable() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async fetchData({ currentPage, pageSize }) {
        const params = {
          ...this.query,
          currentPage,
          pageSize,
          contractStatus: 2,
          templateId: this.temp.templateId
        }
        if (this.param) {
          params[this.qType] = this.param
        }
        if (this.operatorUser) {
          params['operatorUser'] = this.operatorUser
        }
        if (this.date && this.date.length === 2) {
          if (this.dateType === 1) {
            params['signDateStart'] = this.date[0]
            params['signDateEnd'] = this.date[1]
          } else {
            params['expiryDateStart'] = this.date[0]
            params['expiryDateEnd'] = this.date[1]
          }
        }
        const res = await queryEableContractTemplateNotSignedList(params)
        console.log('res', res)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      // 详情
      async openDetail(row) {
        this.$refs.pactInfo.open(row)
      },
      // 上传附件
      uploadAttachment(row) {
        console.log('上传附件')
      },
      // 历史记录
      changeRecord(row) {
        console.log('历史记录', row)
        this.$refs.orderFlow.open(row.contractId)
      },
      // 附件
      showAttachmentListWin(row) {
        console.log('附件', row)
        this.$refs.affixList.open(row)
      },
      // 导出
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.tableData.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          queryEableContractExport({
            type: 2,
            paramInfo: _this._getQuery(_this.query),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
          })
      },
      reset() {
        this.visible = false
        this.temp = {}
        this.date = []
        this.qType = 'csmCode'
        this.operatorUser = ''
        this.tableData.data = []
        this.dateType = 1
        this.param = ''
        this.query = {
          orgSNNo: ''
        }
      },
      // 清除对象空属性
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>
